﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web.Security;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using Maticsoft.Common;
using DQYT.HTDZ.DBUtility;
using DQYT.HTDZ.BusinessService;
using System.Xml;
using System.Text;
using System.Drawing;
using DQYT.HTDZ.Common;
using DQYT.HTDZ.BLL;
using DQYT.HTDZ.Model;
using System.Threading;


namespace DQYT.HTDZ.Web.Views.SJCJTEXT
{
    /// <summary>
    /// 测试txt文本文件提取数据
    /// </summary>
    public partial class SJCJTextTest : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //初始化下拉框数据项
                InitDataSource();
            }

        }
        /// <summary>
        /// 文件格式选择菜单值改变触发事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlTextType_SelectedIndexChanged(object sender, EventArgs e)
        {
            #region
            switch (ddlTextType.SelectedValue)
            {
                case "Txt":
                     hfdUploadFile.Visible = true;
                    fulFileUpload.Enabled = true;
                    break;
                case "Word":
                     hfdUploadFile.Visible = true;
                    fulFileUpload.Enabled = true;
                    break;

            #endregion
            }
        }
        /// <summary>
        /// 文件内容格式选择菜单值改变触发事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlTextValueType_SelectedIndexChanged(object sender, EventArgs e)
        {
            #region
            switch (ddlTextValueType.SelectedValue)
            {
                case "长数据帧131":
                    hfdUploadFile.Visible = true;
                    fulFileUpload.Enabled = true;
                    break;
                case "短数据帧89":
                    hfdUploadFile.Visible = true;
                    fulFileUpload.Enabled = true;
                    break;
                default:
                    break;

            #endregion
            }
        }
        /// <summary>
        /// 文件上传内容框内容改变时触发该事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void hfdUploadFile_ValueChanged(object sender, EventArgs e)
        {
            

        }
        /// <summary>
        /// 上传数据按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnUploadData_Click(object sender, EventArgs e)
        {
            this.lab_wait.Visible = true;
            this.btnUploadData.Enabled = false;

            string sTextType = "";  //文件格式
            string sFileName = fulFileUpload.FileName.Trim().ToString().ToLower(); //上传的文件全名
            
            if (string.IsNullOrWhiteSpace(sFileName))
            {
                MessageBox.Show(this, "请先上传数据文件！");
                return;
            }
            string sTextName=sFileName.Substring(0,sFileName.Length-4);
            string sFilePath = fulFileUpload.PostedFile.FileName;
            
                //判断文件类型数据完整性
                switch (ddlTextType.SelectedValue.Trim().ToString())
                {

                    case "Txt":
                        sFileName = fulFileUpload.FileName.Trim().ToString().ToLower();
                        if (sFileName == "")
                        {
                            JScript.Alert(this, "请选择本地数据文件。");
                            return;
                        }
                        sTextType = Path.GetExtension(sFileName);
                        if (sTextType != ".txt")
                        {
                            JScript.Alert(this.Page, "文件格式不对,请选择Txt文件！");
                            return;
                        }

                        break;
                    case "Word":
                        sFileName = fulFileUpload.FileName.Trim().ToString().ToLower();
                        if (sFileName == "")
                        {
                            JScript.Alert(this, "请选择本地数据文件！");
                            return;
                        }
                        sTextType = sFileName.Substring(sFileName.Length - 4);
                        if (sTextType != ".doc")
                        {
                            JScript.Alert(this.Page, "文件格式不对,请选择Word数据文件！");
                            return;
                        }
                        break;

                    default:
                        break;
                }
                //根据内容格式选择不同的xml配置文件上传数据
                switch (ddlTextValueType.SelectedValue.Trim().ToString())
                {

                    case "长数据帧131":
                        {
                            sFileName = fulFileUpload.FileName.Trim().ToString().ToLower();
                            SJCJTextBLL sjcjTextBll = new SJCJTextBLL("long131", fulFileUpload.PostedFile.InputStream, sTextName);
                            BDDATESOURCEModel model = new BDDATESOURCEModel();
                            BDDATESOURSEBLL bll = new BDDATESOURSEBLL();
                            model = sjcjTextBll.getBbDatasourceModel();
                            BDValueFunc valueFunc = new BDValueFunc();
                            valueFunc.setValue(model);
                            //判断要采集数据是否已经存在
                            DateTime kssj = model.KSSJ.HasValue ? model.KSSJ.Value : DateTime.Now;
                            StandardService service = new StandardService();
                            if (!service.Exists_idDate(model.WELLID, kssj))
                            {
                                this.lab_wait.Visible = false;
                                this.btnUploadData.Enabled = true;
                                JScript.Alert(this.Page, "该数据已存在，请选择其它文件！");
                            }
                            else
                            {
                                bll.Add(model);
                                this.lab_wait.Visible = false;
                                this.btnUploadData.Enabled = true;

                                {
                                    //返回父页面一个值Y
                                    string strScript = "<script language=javascript>top.window.returnValue=";
                                    strScript += "\"Y\"" + ";top.window.close(this);</script>";

                                    Response.Write(strScript);

                                }
                                //JScript.Alert(this.Page, "数据导入成功！");
                            }

                                break;
                            
                        }
                    case "短数据帧89":
                        {
                            sFileName = fulFileUpload.FileName.Trim().ToString().ToLower();
                            SJCJTextBLL sjcjTextBll = new SJCJTextBLL("short89", fulFileUpload.PostedFile.InputStream, sTextName);
                            BDDATESOURCEModel model = new BDDATESOURCEModel();
                            BDDATESOURSEBLL bll = new BDDATESOURSEBLL();
                            model = sjcjTextBll.getBbDatasourceModel();
                            BDValueFunc valueFunc = new BDValueFunc();
                            valueFunc.setValue(model);
                            //判断要采集数据是否已经存在
                            DateTime kssj = model.KSSJ.HasValue ? model.KSSJ.Value : DateTime.Now;
                            StandardService service = new StandardService();
                            if (!service.Exists_idDate(model.WELLID, kssj))
                            {
                                JScript.Alert(this.Page, "该数据已存在，请选择其它文件！");
                            }
                            else
                            {
                                bll.Add(model);

                                {
                                    //返回父页面一个值Y
                                    string strScript = "<script language=javascript>top.window.returnValue=";
                                    strScript += "\"Y\"" + ";top.window.close(this);</script>";

                                    Response.Write(strScript);

                                }
                                //JScript.Alert(this.Page, "数据导入成功！");
                            }

                            break;
                        }

                    default:
                        break;
                }
          
            

        }
        /// <summary>
        /// 填充数据源ddl下拉列表框
        /// </summary>
        private void InitDataSource()
        {
            #region
            ddlTextType.Items.Clear();
            ddlTextValueType.Items.Clear();
            ddlTextType.Items.Add("Txt");
            ddlTextType.Items.Add("Word");
            ddlTextValueType.Items.Add("长数据帧131");
            ddlTextValueType.Items.Add("短数据帧89");
            #endregion
        }
        
    }

    /// <summary>
    /// 文本数据采集核心类
    /// </summary>
    public class SJCJTextBLL
    {
        private string fileName; //文件名，文件名就是井名
        private string formatName;//内容格式名，也是配置文件中的某个内容格式的匹配名
        private FileStream fileStream;//数据流，保存着某次采集的所有信息
        private Stream _stream; 
        private StreamReader streamReader;//文本读取流，保存转换好格式后的文件流
        private XmlDocument xmlDocument;
        private HexStrToDec hexStrToDec;//工具类，十六进制字符串转换成十进制数
        private List<CJSJModel> cjsjModels;//存放采集数据集合
        private BDDATESOURCEModel BbDatasourceModel;
        private CjsjParser cjsjParser;//工具类，转换采集数据
        /// <summary>
        /// 重写的构造函数，在实例化时将内容格式名和数据流传进来
        /// </summary>
        /// <param name="formatName">内容格式名</param>
        /// <param name="fileStream">数据流</param>
        public SJCJTextBLL(string formatName, Stream fileStream, string fileName)
        {
            this.fileName = fileName;
            string configFilePath = string.Concat(System.AppDomain.CurrentDomain.BaseDirectory
                , @"SJCJDataFile\ClientTextConfig\", formatName, ".xml");
            this.formatName = formatName;
            //this.fileStream = fileStream;
            this._stream = fileStream;
            this.streamReader = new StreamReader(_stream, System.Text.Encoding.GetEncoding("GB2312"));
            this.xmlDocument = new XmlDocument();
            this.xmlDocument.Load(configFilePath);
            this.hexStrToDec = new HexStrToDec();
            this.cjsjModels = new List<CJSJModel>();
            this.BbDatasourceModel = new BDDATESOURCEModel();
            this.cjsjParser = new CjsjParser();
        }
        /// <summary>
        /// 获取采集文本中的用来记录采集文本中标识静态数据字段字段信息的，如开始采集时间、井号等
        /// </summary>
        public void getHeadNodes()
        {
            List<SJCJTextHeadNode> headNodes = new List<SJCJTextHeadNode>();//存放head的结点
            XmlNode headNode = this.xmlDocument.SelectSingleNode("//Format[@name= '" + formatName + "'] ");
            headNode = headNode.SelectSingleNode("header");
            int headSize = Convert.ToInt32(headNode.Attributes["size"].Value);
            foreach (XmlNode xn in headNode.ChildNodes)
            {
                SJCJTextHeadNode txtNode = new SJCJTextHeadNode();
                if (!string.IsNullOrEmpty(xn.ChildNodes[0].InnerText))
                {
                    txtNode.StartNum = Convert.ToInt32(xn.ChildNodes[0].InnerText);
                    txtNode.DataName = xn.ChildNodes[1].InnerText;
                    txtNode.DataType = xn.ChildNodes[2].InnerText;
                }

                headNodes.Add(txtNode);
            }
            foreach (SJCJTextHeadNode node_ in headNodes)
            {
                string str = this.streamReader.ReadLine();
                //  if(string.IsNullOrEmpty(str))
                if (node_.DataName == null)
                    continue;
                node_.DataValue = str.Substring(node_.StartNum).Trim();
                //如果文本中的井号是“请输入井号”，就把它换成文件名
                if (node_.DataName == "WELLID")
                    node_.DataValue = this.fileName.Trim().ToString();
            }
            this.BbDatasourceModel.SetPropertyValue(headNodes);
            this.BbDatasourceModel = transBDDATESOURCEModel(this.BbDatasourceModel);
        }
        /// <summary>
        /// 获取记录采集数据中字段信息的，如A相电流、A相电压等
        /// </summary>
        public void getBodyNodes()
        {
            List<SJCJTextBodyNode> bodyNodes = new List<SJCJTextBodyNode>();
            XmlNode bodyNode = this.xmlDocument.SelectSingleNode("//Format[@name= '" + formatName + "'] ");
            bodyNode = bodyNode.SelectSingleNode("body");
            foreach (XmlNode xn in bodyNode.ChildNodes)
            {
                if (string.IsNullOrEmpty(xn.ChildNodes[0].InnerText))
                {
                    break;
                }
                SJCJTextBodyNode dataNode = new SJCJTextBodyNode();
                dataNode.StartNum = Convert.ToInt32(xn.ChildNodes[0].InnerText);
                dataNode.DataSize = Convert.ToInt32(xn.ChildNodes[1].InnerText);
                dataNode.DataName = xn.ChildNodes[2].InnerText;
                dataNode.DataType = xn.ChildNodes[3].InnerText;
                bodyNodes.Add(dataNode);
            }
            while (true)
            {
                string str = streamReader.ReadLine();
                if (string.IsNullOrEmpty(str))
                    break;
                str = str.Substring(bodyNodes[0].StartNum, bodyNodes[0].DataSize).ToString();
                int size = bodyNodes.Count;
                for (int i = 1; i < size; i++)
                {
                    string strHex = str.Substring(bodyNodes[i].StartNum, bodyNodes[i].DataSize).Trim();
                    bodyNodes[i].DataValue = hexStrToDec.HexStr2Dec(strHex).ToString();
                }
                CJSJModel sjcjModel = new CJSJModel();
                sjcjModel.SetPropertyValue(bodyNodes);
                sjcjModel = transSjcjModel(sjcjModel);
                this.cjsjModels.Add(sjcjModel);

            }
        }
        /// <summary>
        /// 得到BDDATESOURCEModel
        /// </summary>
        /// <returns>某次采集的数据</returns>
        public BDDATESOURCEModel getBbDatasourceModel()
        {
            getHeadNodes();
            getBodyNodes();
            this.BbDatasourceModel.CJSJ = BinarySerializer.SerializeObject(this.cjsjModels);
            return this.BbDatasourceModel;
        }
        /// <summary>
        /// 将采集动态数据经过转换算法转换后形成真正能入库的数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public CJSJModel transSjcjModel(CJSJModel model)
        {

            model.AYGGL = cjsjParser.getYGGLParser(model.AYGGL);
            model.BYGGL = cjsjParser.getYGGLParser(model.BYGGL);
            model.CYGGL = cjsjParser.getYGGLParser(model.CYGGL);
            model.PL = cjsjParser.getPLParser(model.PL);
            model.HYGGL = cjsjParser.getYGGLParser(model.HYGGL);
            model.AWGGL = cjsjParser.getWGGLParser(model.AWGGL);
            model.BWGGL = cjsjParser.getWGGLParser(model.BWGGL);
            model.CWGGL = cjsjParser.getWGGLParser(model.CWGGL);
            model.HWGGL = cjsjParser.getWGGLParser(model.HWGGL);
            model.ADY = cjsjParser.getDYParser(model.ADY);
            model.BDY = cjsjParser.getDYParser(model.BDY);
            model.CDY = cjsjParser.getDYParser(model.CDY);
            model.HDY = cjsjParser.getDYParser(model.HDY);
            model.ADL = cjsjParser.getDLParser(model.ADL);
            model.BDL = cjsjParser.getDLParser(model.BDL);
            model.CDL = cjsjParser.getDLParser(model.CDL);
            model.HDL = cjsjParser.getDLParser(model.HDL);
            model.AGLYS = cjsjParser.getGLYSParser(model.AGLYS);
            model.BGLYS = cjsjParser.getGLYSParser(model.BGLYS);
            model.CGLYS = cjsjParser.getGLYSParser(model.CGLYS);
            model.HGLYS = cjsjParser.getGLYSParser(model.HGLYS);
            model.ASZGL = cjsjParser.getASZGLParser(model.ADY, model.ADL);
            model.BSZGL = cjsjParser.getBSZGLParser(model.BDY, model.BDL);
            model.CSZGL = cjsjParser.getCSZGLParser(model.CDY, model.CDL);
            model.HSZGL = cjsjParser.getHSZGLParser(model.ADY, model.BDY, model.CDY);
            model.DJSCNJ = cjsjParser.getDJSCNJParser(model.DJSCNJ);
            model.DJSCZS = cjsjParser.getDJEDZSParser(model.DJSCZS);
            model.DJXL = cjsjParser.getDJXLParser(model.DJXL);
            model.JSJSCNJ = cjsjParser.getJSJSCNJParser(model.JSJSCNJ);
            model.QBZJ = cjsjParser.getQBZJParser(model.QBZJ);
            model.LTWY = cjsjParser.getLTWYParser(model.LTWY);
            model.XDZH = cjsjParser.getXDZHParser(model.XDZH);
            model.YY = cjsjParser.getYYParser(model.YY);
            model.TY = cjsjParser.getTYParser(model.TY);
            model.YMGD = cjsjParser.getYMGDParser(model.YMGD);
            model.WD = cjsjParser.getWDPaser(model.WD);
            model.YGNH = cjsjParser.getYGNHParser(model.YGNHT, model.YGNHW);
            model.WGNH = cjsjParser.getWGNHParser(model.WGNHT, model.WGNHW);

            return model;
        }
        /// <summary>
        /// 将采集静态数据经过转换算法转换后形成真正能入库的数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public BDDATESOURCEModel transBDDATESOURCEModel(BDDATESOURCEModel model)
        {
            model.WELLID = cjsjParser.getWELLIDParser(model.WELLID);
            model.JCRQ = cjsjParser.getJCRQParser(model.JCRQ);
            model.KSSJ = cjsjParser.getKSSJParser(model.KSSJ);
            model.JSSJ = cjsjParser.getJSSJParser(model.JSSJ);
            model.CJZSJ = cjsjParser.getCJZSJParser(model.CJZSJ);
            model.CJPL = cjsjParser.getCJPLParser(model.CJPL);
            model.CJZDS = cjsjParser.getCJZDSParser(model.CJZDS);
            model.SCCDS = cjsjParser.getSCCDSParser(model.SCCDS);
            model.XCCDS = cjsjParser.getXCCDSParser(model.XCCDS);
            model.PULLID = cjsjParser.getPULLIDParser(model.PULLID);
            model.DJID = cjsjParser.getDJIDParser(model.DJID);
            model.PDGID = cjsjParser.getPDGIDParser(model.PDGID);
            model.GLDW = cjsjParser.getGLDWParser(model.GLDW);
            model.JCDW = cjsjParser.getJCDWParser(model.JCDW);
            model.CSR = cjsjParser.getCSRParser(model.CSR);
            model.CJSBXH = cjsjParser.getCJSBXHParser(model.CJSBXH);
            model.CJSBBB = cjsjParser.getCJSBBBParser(model.CJSBBB);
            model.SCRJBB = cjsjParser.getSCRJBBParser(model.SCRJBB);
            return model;
        }
       
      
            
             
      


    }
}